﻿using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.Utils;
using Sustainalytics.Auth.Claims;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using MongoDB.Driver;
using Sustainalytics.ESG.Entities;
using Sustainalytics.MongoDB.Extensions;
using System.Threading.Tasks;
using System.Web.Http.Cors;
using System.Linq;

namespace Sustainalytics.ESGRatings.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ClaimsChecker("api/v1/company/esg")]
    //[AutoInvalidateCacheOutput]
    [LogControllerFilter(true, true, false)] 
    [RoutePrefix("api/v1/company")]
    public class EsgOverallAssessmentController : ApiController
    {


          private OnlineReportAnalystBusinessLogicUnit _service;
    

        public EsgOverallAssessmentController()
        {
            Setup();
        }


       // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("{companyId}/esgOverallAssessment")]
        [UniverseChecker("universeIds", AccountFeature.EsgRatingsOnlineReport)]
        public async Task<HttpResponseMessage> Get(Guid companyId, [FromUri]int[] universeIds = null)
        {
            try
            {
                var database = MongoFactory.GetDatabase(ClientDWConnection.GetConnectionString());
                
                var cdCollection = database.GetCollection<CorporateData>(typeof(CorporateData).Name);
                var cdUniverseIds = cdCollection.Find(cd => cd.Id == companyId)
                    .Project(cd => cd.UniverseIds)
                    .SingleOrDefault();


                if (universeIds == null || cdUniverseIds == null || !cdUniverseIds.Intersect(universeIds.ToList()).Any())
                    throw new ESGReasearchNotInUniversesException();

                var rpCompanyProfile = database.GetCollection<RPCompanyProfile>(typeof(RPCompanyProfile).Name);
              

                var analystCommentary = await _service.GetAnalystCommentary(companyId, universeIds);
                var result = new EsgOverallAssessment { AnalystCommentary = analystCommentary };

                return Request.CreateResponse(HttpStatusCode.OK, result );

            }
            catch (ESGReasearchNotFoundException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message

                });

            }
            catch (ESGReasearchNotInUniversesException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message

                });
            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
           
         
        }

        private void Setup()
        {

            IMongoCollection<Analyst> repository = MongoFactory.GetCollectionFromDatabase<Analyst>(ClientDWConnection.GetConnectionString());

            IMongoCollection<CorporateData> corporateDataRepository = MongoFactory.GetCollectionFromDatabase<CorporateData>(ClientDWConnection.GetConnectionString());

            IMongoCollection<RPCompanyProfile> rpCompanyProfileRepository = MongoFactory.GetCollectionFromDatabase<RPCompanyProfile>(ClientDWConnection.GetConnectionString());

            _service = _service ?? new OnlineReportAnalystBusinessLogicUnit(repository, corporateDataRepository, rpCompanyProfileRepository);
        }
    }
}
